const db = require('../db')

const USER_TABLE = 'zd_users';
const USER_TABLE_FIELDS = 'id,user_name,password,is_admin,sex';

class userService {
    async createUser(id,user_name, password, is_admin,sex) {    
        let sql = `insert into ${USER_TABLE} (${USER_TABLE_FIELDS}) values ('${id}','${user_name}','${password}', '${is_admin}','${sex}');`
        console.log('sql语句:',sql)
        return new Promise((resolve, reject) => {
            db.query(sql, (err, data) => {
                if(err) {
                    console.log('sql错误:', err)
                    reject(err)
                }else{
                    resolve(data)
                }
            })    
        })        
    }
    /**
     * 判断用户名是否已经存在
     * @param {*} user_name 
     */
    async isUserNameExist(user_name) {
        let sql = `select * from ${USER_TABLE} where user_name='${user_name}'`
        console.log('sql语句:',sql)
        return new Promise((resolve, reject) => {
            db.query(sql, (err, data) => {
                if(err) {
                    console.log('sql错误:', err)
                    reject(err)
                }else{
                    resolve(data)
                }
            })
        })
    }
    // 通过用户id来获取用户信息
    async getUserInfoById(id) {
        let sql = `select * from ${USER_TABLE} where id='${id}'`
        console.log('sql语句:',sql)
        return new Promise((resolve, reject) => {
            db.query(sql, (err, data) => {            
                if(err) {
                    console.log('sql错误:', err)
                    reject(err)
                } else {
                    resolve(data)
                }                
            })    
        })   
    }
    /**
     * 通过用户名来获取用户信息
     * @param {*} user_name 
     */
    async getUserInfoByUserName(user_name) {
        let sql = `select * from ${USER_TABLE} where user_name='${user_name}'`
        console.log('sql语句:',sql)
        return new Promise((resolve, reject) => {
            db.query(sql, (err, data) => {            
                if(err) {
                    console.log('sql错误:', err)
                    reject(err)
                } else {
                    resolve(data)
                }                
            })    
        }) 
    }
    /**
     * 根据用户名来获取密码
     * @param {*} user_name 
     */
    async getPasswordByUserName(user_name) {
        // SELECT password FROM `zd_users` where user_name = 'Cellophane004'
        let sql = `SELECT password FROM ${USER_TABLE} WHERE user_name='${user_name}'`
        console.log('sql语句:',sql)
        return new Promise((resolve, reject) => {
            db.query(sql, (err, data) => {
                if(err) {
                    console.log('sql错误:', err)
                    reject(err)
                } else {
                    const password = data[0].password
                    resolve(password)
                }
            })
        })
    }
}

module.exports = new userService()